//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using OpenLS.Spreadsheet.Extensibility;

namespace OpenLS.Spreadsheet.StandardAddIn.Database
{
    internal class DataSource
    {
        private readonly IRange Source;

        public DataSource(IRange source)
        {
            Source = source;
        }

        public bool IsEmpty
        {
            get { return Source.RowSpan == 1; }
        }

        private int GetColumnIndex(string columnName)
        {
            int result;
            if (int.TryParse(columnName, out result))
                return result - 1;
            for (int i = 0; i < Source.ColumnSpan; i++)
            {
                object value = Source[0, i].Value;
                if (value != null && string.Compare(columnName, value.ToString(), StringComparison.CurrentCultureIgnoreCase) == 0)
                    return i;
            }
            throw new NotSupportedException();
        }

        private IEnumerable<double> QueryDoubleImp(string columnName, DatabaseCriteria criteria)
        {
            int columnIndex = GetColumnIndex(columnName);
            for (int i = 1; i < Source.RowSpan; i++)
            {
                if (!criteria.Matches(Source, i))
                    continue;
                object o = Source[i, columnIndex].Value;
                if (o is double) //\\
                    yield return (double) o;
            }
        }

        internal IEnumerable<object> QueryObjectImp(string columnName, DatabaseCriteria criteria)
        {
            int columnIndex = GetColumnIndex(columnName);
            for (int i = 1; i < Source.RowSpan; i++)
            {
                if (!criteria.Matches(Source, i))
                    continue;
                object o = Source[i, columnIndex].Value;
                yield return o;
            }
        }

        public double[] QueryDoublesAsArray(string columnName, IRange criteria, IWorkbook workbook)
        {
            List<double> l =
                new List<double>(QueryDoubleImp(columnName, DatabaseCriteria.Create(workbook, Source,  criteria)));
            double[] result = new double[l.Count];
            l.CopyTo(result);
            return result;
        }

        public object[] QueryObjectsAsArray(string columnName, IRange criteria, IWorkbook workbook)
        {
            List<object> l =
                new List<object>(QueryObjectImp(columnName, DatabaseCriteria.Create(workbook, Source,  criteria)));
            object[] result = new object[l.Count];
            l.CopyTo(result);
            return result;
        }
    }
}